package com.benmei.weike.service;

import com.benmei.weike.dao.DiscountCouponDao;
import com.benmei.weike.dao.MembNewUserScholarshipDao;
import com.benmei.weike.dao.TdNtMemberDao;
import com.benmei.weike.dto.MemberRegisterByCode;
import com.benmei.weike.dto.TdNtInviteByCode;
import com.benmei.weike.dto.TdNtMemberInvite;
import com.benmei.weike.dto.TdNtMemberRegister;
import com.benmei.weike.entity.Assistant;
import com.benmei.weike.entity.DiscountCoupon;
import com.benmei.weike.entity.MembNewUserScholarship;
import com.benmei.weike.util.CommonUtil;
import com.benmei.weike.util.DateUtil;
import com.benmei.weike.util.SMSUtil;
import com.benmei.weike.util.Sms;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Peter on 2018/11/10.
 */
@Service
public class StudentAccountService {
    private static Logger logger = LoggerFactory.getLogger(StudentAccountService.class);
    @Autowired
    private TdNtMemberDao tdNtMemberDao;

    @Autowired
    private MembNewUserScholarshipDao membNewUserScholarshipDao;

    @Autowired
    private DiscountCouponDao discountCouponDao;

    @Transactional
    public RetInfo registerByCode(MemberRegisterByCode member) {
        String logInfo = this.getClass().getName() + ":registerByCode:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = RetInfo.getSuccessInfo();
        Map<String, Object> map = new HashMap<>();
        try {
            TdNtMember memberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(member.getMemb_phone());
            if (memberRegisterSms != null) {
                retInfo.setTip("该手机号码已注册，请更换手机号");
                retInfo.setMark("1");
                return retInfo;
            }
            /**
             * 用户注册
             */
            TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
            tdNtMemberRegister.setMemb_phone(member.getMemb_phone());
            tdNtMemberRegister.setInvite_code(member.getInvite_code());
            tdNtMemberRegister.setMemb_phone_area(member.getMemb_phone_area());
            tdNtMemberRegister.setMemb_islock("1");
            tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
            tdNtMemberRegister.setMemb_phone_area("86");
            tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
            tdNtMemberRegister.setToken(CommonUtil.getToken());
            tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
            tdNtMemberRegister.setMemb_name("nativetalk" + tdNtMemberRegister.getMemb_phone().substring(
                    tdNtMemberRegister.getMemb_phone().length() - 4, tdNtMemberRegister.getMemb_phone().length()
            ));
            tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
            tdNtMemberRegister.setMemb_sex("1");
            tdNtMemberRegister.setUid(UUID.randomUUID().toString());
            tdNtMemberDao.insertTdNtMemberByWeb(tdNtMemberRegister);
            // 分配助教
            Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
            allotAssistant(tdNtMemberRegister.getMemb_id(), sms);

            /**
             * 判断邀请码是否为空，如果邀请码不为空但是没有邀请人，报无效的邀请码
             */
            if (member.getInvite_code() != null) {
                TdNtMemberInvite oldMember = tdNtMemberDao.findTdNtMemberInvite(member.getInvite_code());// 老用户
                TdNtMember newMember = tdNtMemberDao.findTdNtMemberByPhone(member.getMemb_phone()); // 新注册用户
                if (oldMember == null) {
                    //邀请码不存在报错
                    retInfo.setMark("1");
                    retInfo.setTip("无效的邀请二维码");
                    return retInfo;
                }

                if (oldMember.getMemb_id() == newMember.getMemb_id().intValue()) {
                    //邀请人和被邀请人是同一个人
                    retInfo.setMark("1");
                    retInfo.setTip("不能邀请自己");
                    return retInfo;
                }

                /**
                 * 插入邀请的记录
                 */
                TdNtInviteByCode tdNtInviteByCode = new TdNtInviteByCode();
                Timestamp now2 = new Timestamp(System.currentTimeMillis());
                tdNtInviteByCode.setMemb_id(oldMember.getMemb_id());
                tdNtInviteByCode.setInvitee_id(newMember.getMemb_id());
                tdNtInviteByCode.setCreate_date(now2);
                tdNtInviteByCode.setUpdate_date(now2);
                tdNtMemberDao.insertInviteByCode(tdNtInviteByCode);

                //判断新用户有没有领取优惠券，没有的话默认领取
                int reserve_package = tdNtMemberDao.findUseReservePackage(newMember.getMemb_id());
                Date date = DateUtil.createDate("2018-06-01 00:00:00");
                if (reserve_package == 0 && newMember.getMemb_register_time().after(date)) {
                    //用户领取红包
                    // 1. 添加红包领取记录
                    MembNewUserScholarship pojo = new MembNewUserScholarship(newMember.getMemb_id());
                    membNewUserScholarshipDao.insert(pojo);

                    // 2.添加到优惠券表中
                    DiscountCoupon discountCoupon = new DiscountCoupon();
                    discountCoupon.setCourse_type(1);
                    discountCoupon.setMemb_id(newMember.getMemb_id());
                    discountCoupon.setDeleted(0);
                    discountCoupon.setOver((double) 0);
                    discountCoupon.setSubtract((double) 120);
                    discountCoupon.setDiscount_state(0);
                    discountCouponDao.insertDiscountCoupon(discountCoupon);
                    map.put("discountCoupon", discountCoupon);
                }
                map.put("memb_phone", member.getMemb_phone());
                retInfo.setObj(map);
            }
        } catch (Exception e) {
            retInfo.setMark("1");
            retInfo.setTip("网络被外星人劫持");
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    // 分配助教,发送助教老师信息给学生
    public synchronized void allotAssistant(Integer memb_id, Sms sms) {
        logger.info("分配助教 ----------");
        // 查询接单数最少的助教
        Assistant assistant = tdNtMemberDao.findAssistantForMinMembSize();
        logger.info("分配助教 【1】查询接单数最少的助教----------");
        // 设置助教
        tdNtMemberDao.assistantToMemb(memb_id, assistant.getId(), assistant.getName());
        logger.info("分配助教 【2】设置助教----------");
        // 助教人数加1
        tdNtMemberDao.updateAssistantStudentSizePlus(assistant.getId());
        logger.info("分配助教 【3】助教人数加1----------");

        // 发送短信，告诉学生助教老师的联系方式
        if (StringUtils.isNotBlank(sms.getMemb_phone())) {
            // 【外教君】您已成功注册外教君，如需咨询请添加您专属助教老师 Robin，微信（手机同号）：13900001234
            String content = "您已成功注册外教君账号，如需咨询请添加您专属助教老师" + assistant.getName() + "，微信（手机同号）：" + assistant.getWeixin();
            SMSUtil.sendSms(sms, content);
        }
    }

    // 登陆 或 注册
    public RetInfo registerOrLoginByPhoneAndCode(String memb_phone, Integer code) {
        RetInfo retInfo = RetInfo.getSuccessInfo();
        Map<String, Object> map = new HashMap<>();
        try {
            TdNtMember oldMember = tdNtMemberDao.findTdNtMemberRegisterSms(memb_phone);
            if (oldMember != null) {
                map.put("token", oldMember.getToken());
                map.put("memb_id", oldMember.getMemb_id());
                retInfo.setObj(map);
                return retInfo;
            }
            /**
             * 用户注册
             */
            TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
            tdNtMemberRegister.setMemb_phone(memb_phone);
            tdNtMemberRegister.setMemb_islock("1");
            tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
            tdNtMemberRegister.setMemb_phone_area("86");
            Date now = new Date();
            tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(now));
            tdNtMemberRegister.setToken(CommonUtil.getToken());
            tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
            tdNtMemberRegister.setMemb_name("nativetalk" + memb_phone.substring(memb_phone.length() - 4, memb_phone.length()));
            tdNtMemberRegister.setMemb_birthday(new Timestamp(now.getTime()));
            tdNtMemberRegister.setMemb_sex("1");
            tdNtMemberRegister.setUid(UUID.randomUUID().toString());
            tdNtMemberDao.insertTdNtMemberByWeb(tdNtMemberRegister);
            // 分配助教
            Sms sms = new Sms(tdNtMemberRegister.getMemb_phone(), tdNtMemberRegister.getMemb_phone_area());
            allotAssistant(tdNtMemberRegister.getMemb_id(), sms);

            // 2.添加体验券
            DiscountCoupon discountCoupon = new DiscountCoupon();
            discountCoupon.setCourse_type(1);
            discountCoupon.setMemb_id(tdNtMemberRegister.getMemb_id());
            discountCoupon.setDeleted(0);
            discountCoupon.setOver((double) 0);
            discountCoupon.setSubtract((double) 120);
            discountCoupon.setDiscount_state(0);
            discountCouponDao.insertDiscountCoupon(discountCoupon);
            map.put("token", tdNtMemberRegister.getToken());
            map.put("memb_id", tdNtMemberRegister.getMemb_id());
            retInfo.setObj(map);
            return retInfo;
        } catch (Exception e) {
            retInfo.setMark("1");
            retInfo.setTip("网络被外星人劫持");
            logger.error(e.getMessage(), e);
            return retInfo;
        }
    }
}
